//
//  QRVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/14.
//

import UIKit

class QRVC: BaseVC {

    @IBOutlet weak var img: UIImageView!
    @IBOutlet weak var qrImg: UIImageView!
    @IBOutlet weak var nameLab: UILabel!
    
    var userInfo = DMCCUser()
    var con = DMCCConversation()
    var isGroup = Bool()
    var isUser = Bool()
    
    init(with conversation: DMCCConversation, isGroup: Bool, isUser: Bool) {
        super.init(nibName: nil, bundle: nil)
        self.isGroup = isGroup
        self.isUser = isUser
        self.con = conversation
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        if isGroup {
            let group = gosnGroup.getGroupInfoDefault(self.con.targetId)
            self.img.sd_setImage(with: URL(string: group.portrait), placeholderImage: kUserImage)
            self.nameLab.text = group.name
            self.createQRImg(str: self.con.targetId)
        }else if isUser {
            self.userInfo = gosnUser.getUserInfoDefault(con.targetId)
            self.img.sd_setImage(with: URL(string: self.userInfo.portrait), placeholderImage: kUserImage)
            self.nameLab.text = self.userInfo.getAlias()
            self.createQRImg(str: self.userInfo.userId)
        }else {
            self.userInfo = gosnUser.getUserInfoDefault("")
            self.img.sd_setImage(with: URL(string: self.userInfo.portrait), placeholderImage: kUserImage)
            self.nameLab.text = self.userInfo.getAlias()
            self.createQRImg(str: self.userInfo.userId)
        }
        
    }
    
    func createQRImg(str:String) {
        var qrStr = ""
        if isGroup {
            qrStr = "ospn://group/\(str)"
//            qrStr = [NSString stringWithFormat:@"ospn://group/%@", stringcode];
        } else {
            qrStr = "ospn://user/\(str)"
        }
        qrImg.image =  qrStr.createQRImage(size: 300)
    }

    @IBAction func copyClick(_ sender: Any) {
        if isGroup {
            UIPasteboard.general.string = self.con.targetId
        }else{
            UIPasteboard.general.string = self.userInfo.userId
        }
        MHAlert.showMessage("已复制到剪贴板")
    }
    
    @IBAction func saveImg(_ sender: Any) {
        self.saveImageToPhotosAlbum(image: self.qrImg.image!)
    }
    
    func saveImageToPhotosAlbum(image: UIImage) {
        // 确保应用有权访问相册
        PHPhotoLibrary.requestAuthorization { status in
            if status == .authorized {
                // 保存图片到相册
                UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
                DispatchQueue.main.async{
                    MHAlert.showMessage("已保存到系统相册")
                }
            }
        }
    }
    
    /*
    // MARK: - Navigation
 
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension String {
    public func createQRImage(size: CGFloat) -> UIImage? {
        let strData = self.data(using: .utf8, allowLossyConversion: false)
        // 创建一个二维码的滤镜
        guard let qrFilter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
        qrFilter.setValue(strData, forKey: "inputMessage")
        qrFilter.setValue(size <= 150 ? "L" : "H", forKey: "inputCorrectionLevel")
        let qrCIImage = qrFilter.outputImage
        // 创建一个颜色滤镜,黑白色
        guard let colorFilter = CIFilter(name: "CIFalseColor") else { return nil }
        colorFilter.setDefaults()
        colorFilter.setValue(qrCIImage, forKey: "inputImage")
        colorFilter.setValue(CIColor.black, forKey: "inputColor0")
        colorFilter.setValue(CIColor.white, forKey: "inputColor1")
        
        guard let outputImage = colorFilter.outputImage else { return nil }
        let scale = size / outputImage.extent.size.width
        let image_tr = outputImage.transformed(by: CGAffineTransform(scaleX: scale, y: scale))
        let qrImage = UIImage(ciImage: image_tr)
        return qrImage
    }
}
